package com.itheima.filter;

import com.itheima.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //如果本次请求的资源路径是/login，说明是登录请求，直接放行
        String uri = req.getRequestURI();
        if ("/login".equals(uri)) {
            log.info("登录请求，直接放行");
            chain.doFilter(request,response);
            return;
        }

        //如果未登录（本次请求没有携带令牌）：则不允许访问，直接返回401状态码、不放行
        //  前端发请求时会将令牌设置到请求头token中 携带到服务端，所以我们获取请求头token即可
        String token = req.getHeader("Token");
        if (token == null || "".equals(token)) {
            log.warn("未登录，不允许访问");
            resp.setStatus(401);
            return;
        }

        //如果令牌过期或非法：则不允许访问，直接返回401状态码、不放行
        try {
            Claims claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            log.warn("令牌过期或非法，不允许访问");
            resp.setStatus(401);
            e.printStackTrace();
            return;
        }

        //放行
        chain.doFilter(request, response);
    }
}
